import {
  getDetailMenu,
  editUserMenus
} from '../../api/index'
Page({
  data: {
    loading: true,
    // 菜谱封面
    bgImg: '',
    // 菜谱名称
    menuName: '',
    // 菜谱介绍
    menuDesc: '',
    // 食材数组
    foodsList: [{
      id: (new Date).getTime(),
      food: '',
      quantity: '',
    }],
    // 步骤数组
    stepsList: [{
      id: (new Date).getTime(),
      img: '',
      desc: ''
    }],
    // 分类数组
    classifyList: [],
    // 菜谱小贴士
    menuTips: '',
  },
  // 不会作用到视图的数据
  $data: {
    id: ''
  },
  onLoad: function (options) {
    this.$data.id = options.id
    getDetailMenu({
      id: options.id
    }).then(res => {
      this.setData({
        loading: false,
        bgImg: res.data.bgImg,
        menuName: res.data.menuName,
        menuDesc: res.data.menuDesc,
        foodsList: res.data.foodsList.length > 0 ? res.data.foodsList : this.data.foodsList,
        stepsList: res.data.stepsList,
        classifyList: res.data.classifyList,
        menuTips: res.data.menuTips
      })
    })
  },

  // 上传封面图片
  uploadBg(event) {
    wx.showLoading({
      title: '上传中',
      mask: true
    })
    const filePath = event.detail.url
    wx.cloud.uploadFile({
      cloudPath: 'menu_bg_' + new Date().getTime() + '.png', // 上传至云端的路径
      filePath, // 小程序临时文件路径
      success: res => {
        wx.hideLoading()
        // 返回文件 ID
        this.data.bgImg = res.fileID
      },
      fail: console.error
    })
  },
  // 移除封面图片
  removeBg() {
    this.data.bgImg = ''
  },
  // 编辑菜谱名称
  editMenuName(e) {
    this.data.menuName = e.detail.value
  },
  // 编辑菜谱介绍
  editMenuDesc(e) {
    this.data.menuDesc = e.detail.value
  },
  // 添加食材
  addFood() {
    this.data.foodsList.push({
      id: (new Date).getTime(),
      food: '',
      quantity: '',
    })
    this.setData({
      foodsList: this.data.foodsList
    })
  },
  // 删除食材
  deleteFood(e) {
    let index = e.currentTarget.dataset.index
    if (this.data.foodsList.length > 1) {
      this.data.foodsList.splice(index, 1)
      this.setData({
        foodsList: this.data.foodsList
      })
    } else {
      wx.lin.showMessage({
        type: 'error',
        content: '只有一个食材不允许删除'
      })
    }
  },
  // 编辑用料食材
  editFood(e) {
    let index = e.currentTarget.dataset.index
    this.data.foodsList[index].food = e.detail.value
  },
  // 编辑用料用量
  editQuantity(e) {
    let index = e.currentTarget.dataset.index
    this.data.foodsList[index].quantity = e.detail.value
  },

  // 添加步骤
  addStep() {
    this.data.stepsList.push({
      id: (new Date).getTime(),
      img: '',
      desc: ''
    })
    this.setData({
      stepsList: this.data.stepsList
    })
  },
  // 删除步骤
  deleteStep(e) {
    let index = e.currentTarget.dataset.index
    if (this.data.stepsList.length > 1) {
      this.data.stepsList.splice(index, 1)
      this.setData({
        stepsList: this.data.stepsList
      })
    } else {
      wx.lin.showMessage({
        type: 'error',
        content: '只有一个步骤不允许删除'
      })
    }
  },
  // 上传步骤图片
  uploadStepImg(event) {
    wx.showLoading({
      title: '上传中',
      mask: true
    })
    const index = event.currentTarget.dataset.index
    const filePath = event.detail.url
    wx.cloud.uploadFile({
      cloudPath: 'menu_step_' + new Date().getTime() + '.png', // 上传至云端的路径
      filePath, // 小程序临时文件路径
      success: res => {
        wx.hideLoading()
        // 返回文件 ID
        this.data.stepsList[index].img = res.fileID
      },
      fail: console.error
    })

  },
  // 移除步骤图片
  removeStepImg(e) {
    let index = e.currentTarget.dataset.index
    this.data.stepsList[index].img = ''
  },
  // 编辑步骤描述
  editStepDesc(e) {
    let index = e.currentTarget.dataset.index
    this.data.stepsList[index].desc = e.detail.value
  },

  // 编辑菜谱小贴士
  editMenuTips(e) {
    this.data.menuTips = e.detail.value
  },

  // 跳转分类选择
  goClassify() {
    wx.navigateTo({
      url: '/pages/AddClassify/index?list=' + JSON.stringify(this.data.classifyList),
    })
  },

  // 提交前验证数据
  checkData(sendData) {
    let errMsg = ''
    if (!sendData.bgImg) {
      errMsg = '请上传菜谱封面！'
    }

    if (!sendData.menuName) {
      errMsg = '请上传菜谱名称！'
    }

    if (errMsg) {
      wx.lin.showMessage({
        type: 'error',
        content: errMsg
      })
      return false
    } else {
      return true
    }


  },

  // 提交菜谱
  postMenu() {
    const {
      nickName,
      avatarUrl
    } = wx.getStorageSync('userinfo')
    const sendData = {
      ...this.data,
      nickName,
      avatarUrl
    }

    if (!this.checkData(sendData)) {
      return
    }

    sendData.id = this.$data.id
    // 过滤空的食材对象和空的步骤对象
    sendData.foodsList = sendData.foodsList.filter(item => (item.food !== '' || item.quantity !== ''))
    sendData.stepsList = sendData.stepsList.filter(item => (item.img !== '' || item.desc !== ''))

    wx.showLoading({
      title: '上传中',
      mask: true
    })
    editUserMenus(sendData).then(res => {
      wx.hideLoading()
      const pages = getCurrentPages()
      const prePage = pages[pages.length - 2] //上一个页面
      sendData._id = sendData.id
      prePage.onEditSuccess(sendData)
      wx.lin.showMessage({
        type: 'success',
        content: '更新成功',
        duration: 1000,
        success: function () {
          wx.navigateBack({
            delta: 1,
          })
        }
      })
    })
  },

})